const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
	
	const wxContext = cloud.getWXContext()
	let staff = await db.collection('staff').field({
		group_id: true,
		rule_setting: true
	}).where({
		_openid: wxContext.OPENID,
		shop_id: event.shop_id,
	}).get()
	if(staff.data.length==0){
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	staff = staff.data[0]
	
	if (staff.group_id == 3 || (staff.group_id == 2 && !staff.rule_setting)) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	let shop
	if(event.op=='submit'){
		shop = await db.collection('shop').doc(event.shop_id).field({
			status:true
		}).get()
	}else{
		shop = await db.collection('shop').doc(event.shop_id).field({
			name: true,
			address: true,
			location: true,
			phone: true,
			is_show: true,
			is_visit: true,
			cover_image: true,
			content: true,
			status:true
		}).get()
	}
	
	shop = shop.data
	if (!shop) {
		return {
			code: 20002,
			msg: '门店不存在'
		}
	}
	if (shop.status != 2) {
		return {
			code: 20004,
			msg: '门店尚未审核通过'
		}
	}
	if(event.op=='submit'){
		let update = {
			name:event.name,
			address:event.address,
			location:event.location,
			phone:event.phone,
			is_show:event.is_show,
			is_visit:event.is_visit,
			content:event.content,
			cover_image:event.cover_image
		}
		let forms = {
			name: '名称',
			address: '地址',
			location: '坐标',
			cover_image: '门店照片'
		}
		for (var x in forms) {
			if (!event[x]) {
				return {
					code: 20001,
					msg: '请传入' + forms[x]
				}
			}
		}
		update.location = db.Geo.Point(update.location.longitude, update.location.latitude)
		await db.collection('shop').doc(event.shop_id).update({
			data: update
		})
		shop = await db.collection('shop').doc(event.shop_id).field({
			name: true,
			address: true,
			location: true,
			phone: true,
			is_show: true,
			is_visit: true,
			cover_image: true,
			content: true,
			status:true
		}).get()
	}
	return {
		code: 200,
		data: shop
	}
}